package com.huiquan.section.service;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.dao.StaticDataDao;
import com.huiquan.framework.domain.StaticData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.RespHeaderUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.domain.IcdDiseaseGaoge;
import com.huiquan.section.dao.SectionCodeDao;
import com.huiquan.section.dao.SectionDnnDisableDao;
import com.huiquan.section.domain.SectionBlack;
import com.huiquan.section.domain.SectionDnnDisable;

@Service
public class SectionDnnDisableService extends BaseService {

	@Autowired
	private SectionDnnDisableDao sectionDnnDisableDao;
	@Autowired
	private SectionCodeDao sectionCodeDao;
	@Autowired
	private StaticDataDao staticDataDao;

	public ModelAndView list(String startStr, String nameKey, String exactSearchFlag, String countPerPageStr,
			String section, String checkFlag) {

		Map<String, Object> param = new HashMap<>();
		if (section != null && !section.isEmpty()) {
			if (exactSearchFlag != null && exactSearchFlag.equals("1")) {
				param.put("section", section);
			} else {
				param.put("section", "%" + section + "%");
			}
		}
		param.put("checkFlag", checkFlag);
		int totalSize = sectionDnnDisableDao.retrieveSize(param);

		Map<String, Integer> pageNo;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr, countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr);
		}
		int endPage = pageNo.get("endPage");
		int start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<SectionDnnDisable> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = sectionDnnDisableDao.retrievesList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("section", "科室名称");

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, null);
		map.put("showSearch", showSearch);
		// 查询是否含有新增了同义词但没有新增其他的科室图片之类的
		List<StaticData> sds = staticDataDao.retrieveByCode("SECTION_ADD_WARN");
		List<StaticData> warnList = new ArrayList<>();
		if (sds != null && sds.size() > 0) {
			for (StaticData sd : sds) {
				warnList.add(sd);
			}
		}
		map.put("checkFlag", checkFlag);
		if (warnList.size() > 0) {
			map.put("warn", "1");
			map.put("warnList", warnList);
		}
		return new ModelAndView("section/index", map);
	}

	public void export(HttpServletResponse resp) throws Exception {
		LOGGER.info("export section_dnn_disable begin");
		Map<String, Object> param = new HashMap<>();
		// 获取已校验black列表
		RespHeaderUtil.setXlsxResp(resp, "section_dnn_disable");
		param.put("orderIndex", "check_flag,section_name");
		List<SectionDnnDisable> sectionList = sectionDnnDisableDao.retrievesList(param);		
		if (sectionList == null || sectionList.size() == 0) {
			return;
		}
		Workbook workbook = new XSSFWorkbook(); // 创建文档
		Sheet sheet = workbook.createSheet(); // 创建Sheet
		// 写入文件
		int i = 0;
		for (SectionDnnDisable line : sectionList) {
			Row row = sheet.createRow(i);
			Cell cell1 = row.createCell(0);
			cell1.setCellValue(line.getSectionName());
			Cell cell2 = row.createCell(1);
			cell2.setCellValue(line.getCnt());
			Cell cell3 = row.createCell(2);
			cell3.setCellValue(line.getDisable());
			Cell cell4 = row.createCell(3);
			cell4.setCellValue(line.getAscriptionSection());
			i++;
		}
		OutputStream os = resp.getOutputStream();
		workbook.write(os);
		os.close();
		workbook.close();		
	}

	/**
	 * 批量导入
	 * 
	 * @param user
	 * @param zipFile
	 * @return
	 * @throws IOException
	 */
	public ReturnData insertBatch(User user, MultipartFile file) throws IOException {
		if (file != null) { // 获取文件流，解析文件			
			LOGGER.info("batch begin!");
			InputStream excelIn = file.getInputStream();
			InputStreamReader read = new InputStreamReader(excelIn, "UTF-8"); // 考虑到文本编码
			Workbook workbook = new XSSFWorkbook(excelIn);
			Sheet sheet = workbook.getSheetAt(0);
			List<SectionDnnDisable> insertList = new ArrayList<>();
			//行数
			int j = 0;
			// 处理每一行
			for (Row row : sheet) {
				int i = 0;
				//取出每一行记录
				String sectionName = "";
				String cnt = "";
				String ascriptionSection = "";
				String disable = "";
				for (Cell cell : row) {					
					//第一行跳过
					cell.setCellType(Cell.CELL_TYPE_STRING);
					String word = cell.getStringCellValue().trim();	
					if (i == 0) {
						sectionName = word;
					} else if (i == 1) {
						cnt = word;
					} else if (i == 2) {
						disable = word;
					} else if (i == 3) {
						ascriptionSection = word;
					}
					i++;
				}
				SectionDnnDisable value = new SectionDnnDisable();
				value.setSectionName(sectionName);
				value.setAscriptionSection(ascriptionSection);
				value.setCheckFlag("1");
				value.setCnt(cnt);
				value.setDisable(disable);
				value.setModifierId(user.getUserId() + "");
				if (StringUtils.isNotBlank(ascriptionSection)) {
					// 归属科室必须在国家标准科室中的科室名称
					Map<String, Object> param = new HashMap<>();
					param.put("section", ascriptionSection);
					int count = sectionCodeDao.retrieveSize(param);
					if (count < 1) {
						ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
						rc.setDesc("该归属科室不在国家对应科室中：" + ascriptionSection);
						return ReturnUtil.fail(rc);
					}
				}
				insertList.add(value);
				j++;
			}
			if (insertList.size() > 0) {
				sectionDnnDisableDao.deleteAll();
				sectionDnnDisableDao.batchInsert(insertList);
			}
			if (read != null) {
				read.close();
			}
			return ReturnUtil.success("成功");
		} else {
			ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
			rc.setDesc("文件有误");
			return ReturnUtil.fail(rc);
		}
	}

	public ReturnData changeDisable(String id, String disable, User user) {
		sectionDnnDisableDao.updateDisableById(id, disable, user.getUserId() + "");
		return ReturnUtil.success();
	}

	public ReturnData submitPage(String id, User user) {
		sectionDnnDisableDao.updateCheckFlag(id, user.getUserId() + "");
		return ReturnUtil.success();
	}

	public ReturnData changeAscriptionSection(String id, String ascriptionSection, User user) {
		// 归属科室必须在国家标准科室中的科室名称
		Map<String, Object> param = new HashMap<>();
		param.put("section", ascriptionSection);
		int count = sectionCodeDao.retrieveSize(param);
		if (count < 1) {
			ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
			rc.setDesc("归属科室不在国家对应科室中");
			return ReturnUtil.fail(rc);
		}
		sectionDnnDisableDao.updateAscrptionSection(id, ascriptionSection, user.getUserId() + "");
		return ReturnUtil.success();
	}

}
